package phase01.module3.code.question5;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 玩家类，包含姓名，和手中牌的ArrayList
 * 可以从牌桌摸牌，出牌
 */
public class Player {
    private final int MAX_NUM_OF_CARDS = 17;
    private final String name;

    public String getName() {
        return name;
    }

    private final List<Card> cardsAtHand;

    public Player(String name) {
        this.name = name;
        cardsAtHand = new ArrayList<>(MAX_NUM_OF_CARDS);
    }

    @Override
    public String toString() {
        return name;
    }

    public void showCardsAtHand() {
        Iterator<Card> iterator = cardsAtHand.iterator();
        while (iterator.hasNext()) {
            Card card = iterator.next();
            if (iterator.hasNext()) {
                System.out.print(card + ", ");
            } else {
                System.out.print(card);
            }
        }
        System.out.println();
    }

    public int getNumOfLeftCards() {
        return cardsAtHand.size();
    }

    public void drawCard(Table table) {
        if (cardsAtHand.size() >= MAX_NUM_OF_CARDS) {
            System.out.println("不能再摸牌了!");
        } else {
            Card newCard = table.drawCard();
            int len = cardsAtHand.size();
            if (len > 0) {
                // 二分查找确定摸牌插入位置
                int high = len;
                int mid = len / 2;
                int low = 0;
                while (low < high) {
                    Card curr = cardsAtHand.get(mid);
                    if (newCard.compareTo(curr) < 0) {
                        low = mid + 1;
                        mid = low + (high - low) / 2;
                    } else if (newCard.compareTo(curr) > 0) {
                        high = mid;
                        mid = low + (high - low) / 2;
                    } else {
                        break;
                    }
                }
                cardsAtHand.add(mid, newCard);
            } else {
                cardsAtHand.add(newCard);
            }
        }
    }

    public void playCard(Table table, int[] cardsIndexArray) {
        table.playCard(this, cardsAtHand);
    }
}
